﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZHJ.PerfectOA.Common;
using ZHJ.PerfectOA.Model;
using ZHJ.PerfectOA.Model.Enum;

namespace ZHJ.PerfectOA.WebApp.Controllers
{
    public class HomeController : BaseController
    {
        //
        // GET: /Home/
        IBLL.IUserInfoService UserInfoService { get; set; }
        public ActionResult Index()
        {
            if (LoginUser != null)
            {
                ViewData["LoginUser"] = LoginUser.UName;
            }
            return View();
        }

        /// <summary>
        /// 权限判断
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenus()
        {
            //第一条线来判断，用户---->角色----->权限
            //获取登录用户的信息
            var userInfo = UserInfoService.LoadEntities(u => u.ID == LoginUser.ID).FirstOrDefault();
            //获取登录用户的角色
            var loginRoleInfo = userInfo.RoleInfo;
            //获取登录用户的权限.(菜单权限)
            short actionTypeEnum = (short)ActionInfoTypeEnum.MenuActionTypeEnum;
            var loginActionInfos = (from r in loginRoleInfo
                                    from a in r.ActionInfo
                                    where a.ActionTypeEnum == actionTypeEnum
                                    select a).ToList();

            
            //判断第二条线：用户---->权限
            //拿到用户对应的权限的中间表中的信息
            var userInfoActions = from a in userInfo.R_UserInfo_ActionInfo
                                  select a.ActionInfo;
            //过滤，得到用户的菜单权限
            var userInfoActionInfos = (from a in userInfoActions
                                       where a.ActionTypeEnum == actionTypeEnum
                                       select a).ToList();

            //将两条线获取的权限合并到一个集合中。
            loginActionInfos.AddRange(userInfoActionInfos);

            //找出禁用的权限
            var isForbidAction = (from a in userInfo.R_UserInfo_ActionInfo
                                  where a.IsPass == false
                                  select a.ActionInfoID).ToList();
            //将loginActionInfos集合禁止的权限剔除.
            var loginResultActions = loginActionInfos.Where(a => !isForbidAction.Contains(a.ID));
            //去除重复项
            var loginResultActionInfo = loginResultActions.Distinct(new EqualityComparer());
            var result = from a in loginResultActionInfo
                         select new { icon = a.MenuIcon, title = a.ActionInfoName, url = a.Url };
            //将序列化之后的值返回
            return Json(result, JsonRequestBehavior.AllowGet);


        }
    }
}
